<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">城市绿化带病虫害监测系统</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="Username"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="Password"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登录</el-button>

      <div class="tips">
       <span @click="showRegisterModal" class="register-link">没有账号？立即注册</span>
      </div>


    </el-form>

    <!-- 注册弹窗 -->
    <el-dialog
      :visible.sync="registerVisible"
      width="40%"
      custom-class="register-dialog"
      @close="resetForm"
    >
      <!-- 自定义标题并居中 -->
      <div slot="title" class="dialog-title">
        用户注册
      </div>

      <div class="dialog-body">
        <!-- 上半部分：表单内容 -->
        <div class="form-container">
          <el-form ref="registerForm" :model="registerForm" :rules="registerRules" label-width="80px">

            <!-- 头像 -->
            <el-form-item label="头像" prop="avatar">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :http-request="updateUpload"
                :before-upload="beforeAvatarUpload">
                <img v-if="registerForm.avatar" :src="registerForm.avatar" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <!-- 用户名 -->
            <el-form-item label="用户名" prop="account">
              <el-input v-model="registerForm.account" placeholder="请输入用户名" style="width: 100%; max-width: 300px; margin: 0 auto;" />
            </el-form-item>

            <!-- 密码 -->
            <el-form-item label="密码" prop="password">
              <el-input v-model="registerForm.password" type="password" show-password placeholder="请输入密码" style="width: 100%; max-width: 300px; margin: 0 auto;" />
            </el-form-item>

            <!-- 姓名 -->
            <el-form-item label="姓名" prop="name">
              <el-input v-model="registerForm.name" placeholder="请输入姓名" style="width: 100%; max-width: 300px; margin: 0 auto;" />
            </el-form-item>

            <!-- 性别 -->
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="registerForm.gender" style="display: flex; justify-content: center; margin-top: 14px;">
                <el-radio label="1">男</el-radio>
                <el-radio label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 角色 -->
            <el-form-item label="角色" prop="role">
              <el-radio-group v-model="registerForm.role" style="display: flex; justify-content: center; margin-top: 14px;">
                <el-radio label="3">监测人员</el-radio>
                <el-radio label="2">普通用户</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 邮箱 -->
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="registerForm.email" placeholder="请输入邮箱" style="width: 100%; max-width: 300px; margin: 0 auto;" />
            </el-form-item>

            <!-- 手机号 -->
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="registerForm.phone" placeholder="请输入手机号" style="width: 100%; max-width: 300px; margin: 0 auto;" />
            </el-form-item>

            <!-- 个人介绍 -->
            <el-form-item label="个人介绍" prop="introduce">
              <el-input v-model="registerForm.introduce" type="textarea" rows="4" placeholder="请输入个人介绍" style="width: 100%; max-width: 400px; margin: 0 auto;" />
            </el-form-item>

          </el-form>
        </div>

        <!-- 下半部分：提交按钮 -->
        <div class="form-footer">
          <el-button type="primary" @click="submitRegister" style="width: 200px;">
            注 册
          </el-button>
        </div>
      </div>
    </el-dialog>
    
  </div>

</template>

<script>
import { validUsername } from '@/utils/validate'
import { register, upload } from '@/api/user'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的用户名！'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能小于6位！'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      registerVisible: false, // 控制弹窗是否显示
      registerForm: {
        avatar: '',
        account: '',
        password: '',
        name: '',
        gender: '1',
        email: '',
        phone: '',
        role: '3',
        introduce: ''
      },
      registerRules: {
        account: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }]
      }
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showRegisterModal() {
      this.registerVisible = true;
      // 在下一次 DOM 更新后，将表单容器的滚动条置顶
      this.$nextTick(() => {
        const formContainer = document.querySelector('.form-container');
        if (formContainer) {
          formContainer.scrollTop = 0; // 滚动条置顶
        }
      });
    },
     resetForm() {
      this.$refs.registerForm.resetFields(); // 清除校验状态
      this.registerForm = {
        avatar: '',
        account: '',
        password: '',
        name: '',
        gender: '1',
        email: '',
        phone: '',
        role: '3',
        introduce: ''
      };
    },
    submitRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          console.log('提交注册:', this.registerForm);
          register(this.registerForm).then(response => {
            console.log('注册成功', response);
            if(response.code == 200){
              this.$message({
                message: '注册成功，请登录！',
                type: 'success'
              });
            }else{
              this.$message({
                message: response.data,
                type: 'error'
              });
            }
            this.registerVisible = false; // 关闭弹窗
          }).catch(error => {
            console.error('注册失败', error);
          });
        } else {
          console.log('表单校验失败');
          return false;
        }
      });
    },

    updateUpload(options) {
      const { file } = options;
      const bucket = 'pest-control';             // 固定 bucket
      const objectName = 'image';                // 固定目录名

      upload(file, bucket, objectName)
        .then(response => {
          if (response.code === 200 && response.data) {
            this.registerForm.avatar = response.data; // 接收返回的 URL
            this.$message.success('上传成功');
          } else {
            this.$message.error('上传失败：' + (response.message || '未知错误'));
          }
        })
        .catch(() => {
          this.$message.error('请求出错，请重试');
        });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像大小不能超过 2MB!');
      }

      return isJPG && isLt2M;
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || '/' })
            this.loading = false
            this.$store.dispatch('websocket/initWebSocket', this.loginForm.username)
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('登录失败!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}

.register-dialog {
  background-color: $bg;
  color: $light_gray;
  overflow: hidden;

  .el-dialog__body {
    padding: 0;
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .el-dialog__header {
    display: none; // 隐藏默认标题栏
  }

  .el-dialog__body {
    padding: 30px;
    background-color: $bg;

    .el-form {
      text-align: center;
      max-width: 500px;
      margin: 0 auto;

      .el-form-item {
        background: transparent; // 移除灰色背景
        border: none;
        margin-bottom: 20px;

        .el-form-item__label {
          color: $light_gray;
          font-size: 14px;
          line-height: 1.5;
        }

        .el-input {
          width: 100%;
          max-width: 300px;
          margin: 0 auto;

          ::v-deep input {
            background-color: rgba(255, 255, 255, 0.25); // 微弱深色背景，区别于弹窗背景
            color: grey; // 文字颜色为亮色
            border: 1px solid rgba(255, 255, 255, 0.5); // 增强描边颜色对比度
            caret-color: $light_gray; // 光标颜色保持亮色
            padding: 10px 15px;
            border-radius: 4px;
            height: 47px; // 固定高度

            &:-webkit-autofill {
              box-shadow: 0 0 0px 1000px $bg inset !important;
              -webkit-text-fill-color: $light_gray !important;
            }
          }
        }
      }

      .el-radio-group {
        display: flex;
        justify-content: center;
        gap: 20px;

        .el-radio__label {
          color: $light_gray; // 确保单选按钮文字颜色一致
        }
      }

      .avatar-uploader {
        margin: 0 auto;
        display: block;
        width: fit-content;

        .el-upload {
          border: 1px dashed rgba(255, 255, 255, 0.5); // 增强描边颜色对比度
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          background: rgba(0, 0, 0, 0.1);

          &:hover {
            border-color: #409EFF;
          }

          .avatar-uploader-icon {
            font-size: 28px;
            color: $dark_gray;
            width: 100px;
            height: 100px;
            line-height: 100px;
            text-align: center;
          }

          .avatar {
            width: 100px;
            height: 100px;
            display: block;
          }
        }
      }
    }
  }
}

.dialog-body {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.form-container {
  flex: 1;
  max-height: 300px;
  overflow-y: auto;
  padding: 20px;
  box-sizing: border-box;
}

.form-footer {
  flex-shrink: 0;
  padding: 10px 20px;
  background-color: transparent; // 可选：移除背景色干扰
  text-align: center;
  border-top: 1px solid rgba(100, 100, 100, 0.1); // 上边框
}

::v-deep .el-dialog__wrapper > .register-dialog {
  border-radius: 16px !important;
  max-height: 80vh !important;
  overflow: hidden !important;
}

.dialog-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  color: #454545;
}
</style>
